package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/19 9:26
 */
public class Flink01_Table_BaseUse_Agg {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 1. 创建一个流
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1000L, 10),
            new WaterSensor("sensor_1", 2000L, 20),
            new WaterSensor("sensor_2", 3000L, 30),
            new WaterSensor("sensor_1", 4000L, 40)
        );
        
        // 2. 创建流式表的环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
    
        // 3. 把流转成动态表
        Table table = tEnv.fromDataStream(stream);
        
        // 4. 在动态表上面执行连续查询, 得到新的动态表
    
        /*Table t1 = table
            .groupBy($("id"))
            .aggregate($("vc").sum().as("vc_sum"))
            .select($("id"), $("vc_sum"));*/
        
        Table t1 = table
            .groupBy($("id"))
            .select($("id"), $("vc").sum().as("sum_vc"));
        // 5. 把结果表转成流
//        DataStream<WaterSensor> result = tEnv.toAppendStream(t1, WaterSensor.class);
        DataStream<Tuple2<Boolean, Row>> result = tEnv.toRetractStream(t1, Row.class);
        
        result.filter(t -> t.f0).map(t -> t.f1).print();
    
        env.execute();
    
    }
}
